﻿/*
 * User: Jorge
 * Date: 3/16/2010
 * Time: 11:37 PM 
 */
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;

namespace Utils
{
	[ComVisible(true)]
	public class Encryption : IDisposable
	{
		public string Encrypt(string arg)
		{
            byte[] bytes = Encoding.Unicode.GetBytes(arg);
			byte[] protectedData = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);            
            return ByteArrayToString(protectedData);           
		}
		
		public string Decrypt(string arg)
		{			
			byte[] bytes = StringToByteArray(arg);
			byte[] data = ProtectedData.Unprotect(bytes, null, DataProtectionScope.CurrentUser);
            return Encoding.Unicode.GetString(data);
		}
		
		private string ByteArrayToString(byte[] ba)
		{
		  string hex = BitConverter.ToString(ba);
		  return hex.Replace("-","");
		}
		
		private byte[] StringToByteArray(string hex) 
		{
  			return Enumerable.Range(0, hex.Length).
		         Where(x => 0 == x % 2).
		         Select(x => Convert.ToByte(hex.Substring(x,2), 16)).
		         ToArray();
		}
		
		public void Dispose()
		{
			
		}
	}	
}